package com.xzy.spring.config;

import com.xzy.spring.business.entity.*;
import com.xzy.spring.demo.factorybean.MyFactoryBean;
import com.xzy.spring.demo.registrar.MyImportBeanDefinitionRegistrar;
import com.xzy.spring.demo.selector.MyImportSelector;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.*;

/**
 * @author xzy
 * @date 2021-02-08 11:11
 * 说明：
 */
@Configuration
@PropertySource(value = {"classpath:/application.properties"})
@ComponentScan(value = "com.xzy.spring.*")
@Import(value = {MyImportSelector.class, MyImportBeanDefinitionRegistrar.class})
public class BeansConfig {

    @Bean
    public UserEntity userEntityAnn() {
        return new UserEntity("userEntityAnn", 22);
    }

    /**
     * 单例：默认情况下，IOC容器创建时就创建Bean，之后使用时不再创建新的Bean。
     */
    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
    public UserEntity userEntitySingletonAnn() {
        return new UserEntity("userEntitySingletonAnn", 23);
    }

    /**
     * 懒加载单例Bean
     */
    @Bean
    @Lazy
    @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
    public UserEntity userEntitySingletonLazyAnn() {
        return new UserEntity("userEntitySingletonLazyAnn", 24);
    }

    /**
     * 原型：IOC容器创建时不创建Bean，每次使用时创建新的Bean
     */
    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public UserEntity userEntityPrototypeAnn() {
        return new UserEntity("userEntityPrototypeAnn", 25);
    }

    /**
     * 通过FactoryBean注册Bean
     */
    @Bean
    public MyFactoryBean myFactoryBean() {
        return new MyFactoryBean();
    }

    /**
     * 单例Bean，指定初始化、销毁方法
     */
    @Bean(initMethod = "init", destroyMethod = "destroy")
    @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
    public BaseEntity baseEntitySingleTonAnn() {
        return new BaseEntity("baseEntitySingleTonAnn");
    }

    /**
     * 原型Bean，指定初始化、销毁方法
     */
    @Bean(initMethod = "init", destroyMethod = "destroy")
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public BaseEntity baseEntityPrototypeAnn() {
        return new BaseEntity("baseEntityPrototypeAnn");
    }

    /**
     * 借助InitializingBean和DisposableBean接口，自定义Bean的初始化和销毁流程
     */
    @Bean
    public CatEntity initializingAndDisposableBean() {
        return new CatEntity("initializingAndDisposableBean");
    }

    /**
     * 借助JSR250的@PostConstruct和@PreDestroy注解自定义Bean初始化后、销毁前处理流程
     */
    @Bean
    public DogEntity jsr250() {
        return new DogEntity("dogEntity");
    }

    /**
     * 属性赋值
     */
    @Bean
    public AuthorEntity propertiesAssignment() {
        return new AuthorEntity();
    }
}
